//
//  PhotoScrollView.m
//  TheRoadAD
//
//  Created by 宁宁 on 16/8/18.
//  Copyright © 2016年 baixue. All rights reserved.
//

#import "PhotoScrollView.h"


#define picHeight 60
#define picWidth picHeight / 2 * 3

#define centerPicHeight 100
#define centerPicWidth centerPicHeight / 2 * 3


@implementation PhotoScrollView
{
    NSMutableArray *_buttonArray;
}

- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        
        self.pagingEnabled = NO;//按页滚动
        self.showsHorizontalScrollIndicator = NO;
        
    }
    return self;
}
- (void)layoutSubviews{
    [super layoutSubviews];
}
- (void)setLayout:(NSArray *)picArray andIndex:(int)index{
    if (!_buttonArray) {
        _buttonArray = [NSMutableArray array];
    }
    
    self.contentSize = CGSizeMake(picArray.count * (picWidth + 15), 60);
    
    
    CGFloat contentX = 0;
    CGFloat contentY = 0;
    for (int i = 0; i < picArray.count; i++) {
        UIButton *pic = [UIButton buttonWithType:UIButtonTypeCustom];
        
//        if (i == 0) {
//            pic.frame = CGRectMake(Screen_Width / 2 - picWidth / 2 + i * (picWidth + 20), 0, centerPicWidth, centerPicHeight);
//        }else{
            pic.frame = CGRectMake(Screen_Width / 2 - picWidth / 2 + i * (picWidth + 15), 0, picWidth, picHeight);
//        }
        pic.backgroundColor = [UIColor redColor];
        [pic setImage:[UIImage imageNamed:picArray[i]] forState:UIControlStateNormal];
        pic.layer.borderColor = UIColorFromRGB(0x03DACE).CGColor;
        [pic addTarget:self action:@selector(showPic:) forControlEvents:UIControlEventTouchUpInside];
        
        [_buttonArray addObject:pic];
        [self addSubview:pic];
        
        if (index == i) {
            contentX = pic.frame.origin.x;
            contentY = pic.frame.origin.y;
            
            pic.layer.borderWidth = 2;
        }
    }
    
    self.contentOffset = CGPointMake(contentX - Screen_Width / 2 + picWidth / 2, contentY);
}

- (void)showPic:(UIButton *)sender{
    for (int i = 0; i < _buttonArray.count; i++) {
        UIButton *button = _buttonArray[i];
        CGFloat senderX = sender.frame.origin.x;
        CGFloat senderY = 0;
        sender.frame = CGRectMake(senderX, senderY, picWidth, picHeight);
        button.layer.borderWidth = 0;
        if (sender == button) {
//            [UIView animateWithDuration:1 animations:^{
//                button.frame = CGRectMake(senderX, senderY, centerPicWidth, centerPicHeight);
//            }];
            _showPicClick(i);
            button.layer.borderWidth = 2;
        }
        
        [UIView animateWithDuration:0.2 animations:^{
            self.contentOffset = CGPointMake(senderX - Screen_Width / 2 + picWidth / 2, 0);
        }];
    }
}

@end
